package com.haierp.service.logistics.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Sets;
import com.haierp.exception.ErpCommonException;
import com.haierp.mapper.BrandMapper;
import com.haierp.model.Brand;
import com.haierp.model.ErpOrder;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.IShippingTrackService;
import com.haierp.service.logistics.IHaiDaiBaoService;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.util.HttpClientUtil;
import com.haierp.util.Md5Util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Service("haiDaiBaoService")
public class HaiDaiBaoServiceImpl implements IHaiDaiBaoService {
	@Autowired
	private IShippingOrderService shippingOrderService;
	@Autowired
	private BrandMapper brandMapper;
	@Autowired
	private IShippingTrackService shippingTrackService;
	

	@Override
	public String createOrder(Long id, Long companyId) {
		ShippingOrder shippingOrder = shippingOrderService.selectById(id);
		if (shippingOrder == null) {
			throw new ErpCommonException("发货单号异常");
		}
		List<Map<String, Object>> goodsList = new ArrayList<>();
		Map<String, Object> paramData = new HashMap<String, Object>();
		List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
		if(companyId.compareTo(ErpOrderList.get(0).getCompanyId()) != 0) {
			throw new ErpCommonException("海带宝发货ID有误!");
		}
		ErpOrderList.forEach(erpOrder -> {
			Map<String, Object> goods = new HashMap<String, Object>();
			Map<String,String> Eng = getBrandEg();
			String brandEg = erpOrder.getBrand();
			String ItembrandEg = "";
			for (Map.Entry<String, String> entry : Eng.entrySet()) {
				if (brandEg.contains(entry.getKey())) {
					ItembrandEg = (String) entry.getValue();
				}
			}
			goods.put("GBrand", ItembrandEg);
			goods.put("GName", erpOrder.getItemName());
			goods.put("GCount", erpOrder.getQuantity());
			goods.put("GUnit", erpOrder.getSalePrice());
			goodsList.add(goods);
		});
		paramData.put("UserCode", "SBJZR");
		paramData.put("CenterCode", "US");
		paramData.put("LineCode", "USHDB");
		paramData.put("ExpressId", shippingOrder.getShippingNo());
		paramData.put("Name", shippingOrder.getReceiver());
		paramData.put("Tel", shippingOrder.getTelephone());
		paramData.put("Province", shippingOrder.getReceiverState());
		paramData.put("City", shippingOrder.getReceiverCity());
		paramData.put("Area", shippingOrder.getReceiverDistrict());
		paramData.put("Street", shippingOrder.getAddressDetail());
		paramData.put("CardId", shippingOrder.getIdCard());
		paramData.put("FirstName", "IRUHUA");
		paramData.put("PackageInfo", goodsList);
		String  trueToken = getHaiBaoToken();
		JSONObject description = HttpClientUtil.post("http://webapi.haidaibao.com/api/Forecast/Add?Token="+trueToken, null, paramData,"1");
		//System.err.println(description);
		JSONObject shippingNoJson = JSONObject.fromObject(description);
		String hdbStatus = shippingNoJson.getString("Status");
		if(hdbStatus.equals("200")){
			JSONObject jsonData = shippingNoJson.getJSONObject("Data");
			String hdbNo = jsonData.getString("ExpressId");
			shippingOrder.setLogisticNo(hdbNo);
			shippingOrderService.updateSelectiveById(shippingOrder);
			return shippingNoJson.getString("Msg");
		} 
		return null;


	}

	
	 public static void main(String[] args)  {  
		   /* String  trueToken = getHaiBaoToken();
	        Map<String, Object> paramData = new HashMap<String, Object>();
	    	paramData.put("UserCode", "SBJZR");
			paramData.put("CenterCode", "US");
			paramData.put("LineCode", "USHDB");
			paramData.put("ExpressId", "HDB123456789");
			paramData.put("Name", "陆敏钗");
			paramData.put("Tel", "15088735320");
			paramData.put("Province", "浙江省");
			paramData.put("City", "杭州市");
			paramData.put("Area", "余杭区");
			paramData.put("Street", "文一西路大华海派风范");
			paramData.put("CardId", "440112198708090945");
			paramData.put("FirstName", "654654");
			List<Map<String, Object>> goodsList = new ArrayList<>();
			Map<String, Object> goods = new HashMap<String, Object>();
			goods.put("GName", "润手霜");
			goods.put("GBrand", "coach");
			goods.put("GCount", 1);
			goods.put("GUnit", 26.00);
			goodsList.add(goods);
			paramData.put("PackageInfo", goodsList);
			JSONObject jsonObject = JSONObject.fromObject(paramData);
			JSONObject description = HttpClientUtil.post("http://webapi.haidaibao.com/api/Forecast/Add?Token="+trueToken, null, paramData,"1");//正式环境数据
			//JSONObject description = HttpClientUtil.post("http://120.24.80.151:407/api/Forecast/Add?Token="+trueToken, null, paramData,"1");//测试环境请求
			System.err.println(description);*/
			/*String  trueToken = getHaiBaoToken();
			String  ExpressId = "HDB18040404201564779";
			String  UserCode = "SBJZR";
			String  CnExp = "1";
			String  urlresponse = DimensionCodeUtil.sendGet("http://webapi.haidaibao.com/api/Logistics/Get", "ExpressId=" + ExpressId + "&UserCode=" + UserCode + "&CnExp="+ CnExp + "&Token=" + trueToken);
			JSONObject jsonObject = JSONObject.fromObject(urlresponse);
			String data = jsonObject.getString("Status");
			String msg = jsonObject.getString("Msg");
			String dataStr = jsonObject.getString("Data");
			String dataStr1 = dataStr.substring(1, dataStr.length()-1);
			JSONObject detail = JSONObject.fromObject(dataStr1);
			JSONObject detail1 = detail.getJSONObject("ExpressInfo");
			String shippingNo = detail1.getString("ExpressId");
			JSONArray jsonArray = detail.getJSONArray("HdbLogist");
			ShippingTrack shippingTrack = new ShippingTrack();
			shippingTrack.setShippingNo(shippingNo);
			//查询此发货单的物流轨迹
			EntityWrapper<ShippingTrack> selEntityWrapper = new EntityWrapper<ShippingTrack>();
			selEntityWrapper.where("shipping_no={0}", shippingNo);
			List<ShippingTrack> shippingReadyTracks = shippingTrackService.selectList(selEntityWrapper);
			Set<Integer> statusSet = Sets.newHashSet();
			if(shippingReadyTracks.size()>0) {
				shippingReadyTracks.forEach(item -> {
					statusSet.add(item.getStatus());
				});
			}
	        System.out.println(urlresponse);*/
	    }  
	 
	// 获取海带宝token 
		public static String getHaiBaoToken(){
			String Timestamp = String.valueOf(getSecondTimestamp(new Date()));
			String APIKey = "5D3F911ABF355BF8EB5CB94FC1EF320C38D2DD71CF361BC0720A2289F3F58F225A5244AC51A58D06"; //正式APIKey
			String APISecret = "F7E21BA67B6343F0712D2AA90D3623B7BDBAC408D0B716DC7DFAF6C17C307CC64DD79E70C6D52D4D"; //正式APISecret
			//String APIKey = "6946C05D3A880CAA37B5192D5671AD48C7E9CD1FDB2C47A47E9EC340A0DEDD82BDEC9944C74EB5A8"; //测试APIKey
			//String APISecret = "B4BA291CBC33D61B94DDABC3EB8AC321E3B5CC812B5F674C9B3682CD982275C075702D210081FDF5"; //测试APISecret
			Map<String, String> params = new TreeMap<String, String>();
			params.put("APIKey", APIKey);
			params.put("APISecret", APISecret);
			params.put("Timestamp", Timestamp);
			String APISign = getSign(params);
			String  urlresponse = DimensionCodeUtil.sendGet("http://webapi.haidaibao.com/api/Token/Get", "APIKey=" + APIKey + "&Timestamp=" + Timestamp + "&APISign=" + APISign);
			//String  urlresponse = DimensionCodeUtil.sendGet("http://120.24.80.151:407/api/Token/Get", "APIKey=" + APIKey + "&Timestamp=" + Timestamp + "&APISign=" + APISign);
			JSONObject jsonObject = JSONObject.fromObject(urlresponse);
			JSONObject jsonData = jsonObject.getJSONObject("Data");
			String trueToken = jsonData.getString("Token");
			return trueToken;
		}
		
		//参数名的值默认升序
		private static String getSign(Map<String, String> params) {
			   Map<String, String> sortMap = new TreeMap<String, String>();
			   sortMap.putAll(params);
			   // 以k1=v1&k2=v2...方式拼接参数
			   StringBuilder builder = new StringBuilder();
			   for (Map.Entry<String, String> s : sortMap.entrySet()) {
			       String k = s.getKey();
			       String v = s.getValue();
			       if (StringUtils.isBlank(v)) {// 过滤空值
			           continue;
			       }
			       builder.append(k).append("=").append(v).append("&");
			   }
			   if (!sortMap.isEmpty()) {
			       builder.deleteCharAt(builder.length() - 1);
			   }
			   String  no = builder.toString();
			   return Md5Util.getMD5(builder.toString());
			}
		
		//精确到秒级别
		public static int getSecondTimestamp(Date date){  
		    if (null == date) {  
		        return 0;  
		    }  
		    String timestamp = String.valueOf(date.getTime());  
		    int length = timestamp.length();  
		    if (length > 3) {  
		        return Integer.valueOf(timestamp.substring(0,length-3));  
		    } else {  
		        return 0;  
		    }  
		} 

	public  Map<String, String> getBrandEg() {
			Map<String, String> category = new HashMap<String, String>();
			List<Brand> listBrand = brandMapper.queryAllBrandEg();
				for (Brand brand : listBrand) {
					category.put(brand.getName(), brand.getName());
				}
				return category;

		}


	@Override
	public void shippingTrack(String shipperOrderNo) throws ParseException {
		if(shipperOrderNo == null) {
			throw new ErpCommonException("物流单号异常");
		}
		String  trueToken = getHaiBaoToken();
		String  UserCode = "SBJZR";
		String  CnExp = "1";
		String  urlresponse = DimensionCodeUtil.sendGet("http://webapi.haidaibao.com/api/Logistics/Get", "ExpressId=" + shipperOrderNo + "&UserCode=" + UserCode + "&CnExp="+ CnExp + "&Token=" + trueToken);
        System.out.println(urlresponse);
        JSONObject jsonObject = JSONObject.fromObject(urlresponse);
		String data = jsonObject.getString("Status");
		String msg = jsonObject.getString("Msg");
		String dataStr = jsonObject.getString("Data");
		String dataStr1 = dataStr.substring(1, dataStr.length()-1);
		JSONObject detail = JSONObject.fromObject(dataStr1);
		JSONObject detail1 = detail.getJSONObject("ExpressInfo");
		String shippingNo = detail1.getString("ExpressId");
		JSONArray jsonArray = detail.getJSONArray("HdbLogist");
		ShippingTrack shippingTrack = new ShippingTrack();
		shippingTrack.setShippingNo(shippingNo);
		//查询此发货单的物流轨迹
		EntityWrapper<ShippingTrack> selEntityWrapper = new EntityWrapper<ShippingTrack>();
		selEntityWrapper.where("shipping_no={0}", shippingNo);
		List<ShippingTrack> shippingReadyTracks = shippingTrackService.selectList(selEntityWrapper);
		Set<Integer> statusSet = Sets.newHashSet();
		if(shippingReadyTracks.size()>0) {
			shippingReadyTracks.forEach(item -> {
				statusSet.add(item.getStatus());
			});
		}
		
		
	}
}
